package com.cnswhy.cloud.server.app.controller.customer;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.config.JsApiPay;
import com.cnswhy.cloud.server.app.config.WxPayApi;
import com.cnswhy.cloud.server.app.config.WxPayConfig;
import com.cnswhy.cloud.server.app.config.WxPayData;
import com.cnswhy.cloud.server.core.config.*;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.core.entity.ChargeMoney;
import com.cnswhy.cloud.server.core.entity.Customer;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.ChargeMoneyService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Api(tags = "充值控制层")
@Controller
@RequestMapping("/income")
@Slf4j
public class IncomeMoneyController extends BaseController {

    @Autowired
    private ChargeMoneyService chargeMoneyService;
    @Autowired
    IdGeneratorService idGeneratorService;

    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "查询配置的充值金额", httpMethod = "POST")
    @RequestMapping("/queryChargeMoney")
    @ResponseBody
    public RespVo queryChargeMoney() {
        log.info("查询配置的充值金额");
        RespVo vo = new RespVo();
        try {
            String money = (String) redisService.hget(RedisConstant.SYS_CONFIG_2, RedisConstant.SPELL_CHARGE_MONEY);
            log.info("money:{}", money);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(money);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "保存充值记录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "money", value = "充值金额", required = true),
            @ApiImplicitParam(name = "payType", value = "支付方式1支付宝2微信", required = true)
    })
    @RequestMapping("/saveData")
    @ResponseBody
    public RespVo saveData(BigDecimal money, Integer payType, HttpServletRequest request) {
        log.info("保存充值记录：{} {}", money, payType);

        RespVo vo = new RespVo();
        try {
            if (money.compareTo(BigDecimal.ZERO) < 0) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("充值金额不正确");
                return vo;
            }
            Customer loginCustomer = getLoginCustomer( request);
            ChargeMoney entity = new ChargeMoney();
            entity.setStatus(1);
            entity.setChargeMoney(CnswhyUtil.getFen(money));
            entity.setCustomerId(loginCustomer.getId());
            entity.setPayType(payType);
            entity.setOrderNum(idGeneratorService.genCommonIdString());
            chargeMoneyService.save(entity);
//            String qrCode = "";
//            if (payType.intValue() == 1)
//            {
//                qrCode = (String) redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.PERSION_ALI_QRCODE);
//            }
//            else
//            {
//                qrCode = (String) redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.PERSION_WX_QRCODE);
//            }
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(entity.getOrderNum());
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("充值失败");
            log.error("充值失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "查询充值记录", httpMethod = "POST")
    @ApiParam(name = "bo", value = "充值bo对象")
    @RequestMapping("/ajaxPage")
    @ResponseBody
    public RespVo ajaxPage(ChargeMoney bo,
                           @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("查询充值记录：{} {} {}", JSON.toJSONString(bo), currentPage, pageSize);
        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            bo.setCustomerId(loginCustomer.getId());
            QueryWrapper<ChargeMoney> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByDesc("create_time");
            Page<ChargeMoney> page = new Page<>(currentPage, pageSize);
            IPage<ChargeMoney> pageList = chargeMoneyService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询失败");
            log.error("查询失败", e);
        }
        return vo;
    }


    @ApiOperation(value = "充值拼购券微信支付", httpMethod = "POST")
    @ApiParam(name = "orderNum", value = "订单号")
    @RequestMapping("/wxPay")
    @ResponseBody
    public RespVo wxPay(String orderNum, HttpServletRequest request) {
        log.info("充值拼购券微信支付：{}", orderNum);

        RespVo respVo = new RespVo();
        try {
            String body = "INCOME-CHARGE";
            String payType = "APP";

            //ChargeMoney order = chargeMoneyService.queryByOrderNum(orderNum);
            ChargeMoney order = chargeMoneyService.getOne(Wraps.<ChargeMoney>lbQ().eq(ChargeMoney::getOrderNum, orderNum));

            //BigDecimal multiply = order.getChargeMoney().multiply(new BigDecimal("100"));

            String notifyUrl = (String) redisService.hget(RedisConstant.SYS_CONFIG_1, RedisConstant.WX_NOTIFY_URL);

            JsApiPay jsApiPay = new JsApiPay(null, order.getChargeMoney().intValue(), WxPayConfig.MCH_ID, WxPayConfig.APP_ID,
                    notifyUrl, WxPayConfig.PAY_KEY, "", payType);
            WxPayData wxData = jsApiPay.GetUnifiedOrderResult("乐优团拼购券", "交易编号：" + orderNum, orderNum, body,CnswhyUtil.getHttpServletRequestIpAddress());
            if (StringUtils.equals(wxData.GetValue("return_code").toString(), "SUCCESS")
                    && StringUtils.equals(wxData.GetValue("result_code").toString(), "SUCCESS")) {
                Date beijingDate = Calendar.getInstance(Locale.CHINA).getTime();
                String timeStamp = String.valueOf(beijingDate.getTime() / 1000);
                SortedMap<String, Object> map2 = new TreeMap<String, Object>();
                map2.put("appid", WxPayConfig.APP_ID);
                map2.put("timestamp", timeStamp);
                map2.put("noncestr", wxData.GetValue("nonce_str"));
                map2.put("prepayid", wxData.GetValue("prepay_id"));
                map2.put("package", "Sign=WXPay");
                map2.put("partnerid", wxData.GetValue("mch_id"));
                String paySign = WxPayApi.createSign(map2, WxPayConfig.PAY_KEY);
                map2.put("sign", paySign);
                respVo.setCode(RespVo.CODE_SUCCESS);
                respVo.setResult(map2);

            } else {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("发起微信支付失败");
            }
        } catch (Exception e) {
            log.error("调用微信支付请求异常：", e);
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("发起微信支付失败");
        }

        return respVo;
    }

}
